package com.ysd.ziyuanshiyongtongji.service;

import java.util.List;

import javax.annotation.Resource;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Expression;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import com.ysd.ziyuanshiyongtongji.dao.IAdminDao;
import com.ysd.ziyuanshiyongtongji.dto.AdminDTO;
import com.ysd.ziyuanshiyongtongji.model.Admin;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

/**
 * AdminServiceImpl
 */
@Service
public class AdminServiceImpl implements IAdminService {
 @Resource
     private IAdminDao adminDao;
    @Override
    public Page<Admin> findpage(AdminDTO dto) {
        Sort sort = Sort.by(Sort.Order.asc("id"));
        Pageable page = PageRequest.of((dto.getPage()- 1) * dto.getLimit(), dto.getLimit(), sort);
        return adminDao.findAll(getWhereClause(dto), page);
    }

    private Specification<Admin> getWhereClause(AdminDTO dto) {
        return new Specification<Admin>() {
            @Override
            public Predicate toPredicate(Root<Admin> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
                Predicate p = criteriaBuilder.conjunction();
                List<Expression<Boolean>> exList = p.getExpressions();
                if (dto.getName()!=null &&!"".equals(dto.getName())) {
                    exList.add(criteriaBuilder.like(root.<String>get("name"),"%"+dto.getName()+"%"));   
                }
                if (dto.getPass()!=null &&!"".equals(dto.getPass())) {
                    exList.add(criteriaBuilder.like(root.<String>get("pwd"),"%"+dto.getPass()+"%"));   
                }
               
                return p;
            }

        };
    }

    @Override
    public Admin saveAdmin(Admin a) {
		return adminDao.save(a);
    }

    @Override
    public void del(Integer id) {
        adminDao.deleteById(id);

    }

    @Override
    public List<Admin> findAll() {
       return adminDao.findAll();
    }
}